--
-- Author: shunguo.chen
-- Date: 2019-07-01 20:36:56
--
-- AvatarShopView avatar商店，理发店
--

local Armature = app:getClass("Armature")
local AvatarFactory = app:getClass("AvatarFactory")
local TabsBtn = require("app.widget.TabsBtn")
local ResRender = require("app.widget.renders.ResRender")

local AvatarShopPanel = import(".AvatarShopPanel")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

local AVATAR_SHOP_NAMES = {
    L("barber_shoptips1"), 
    L("barber_shoptips2"), 
    L("barber_shoptips3"), 
    L("barber_shoptips4")
}

ClassRef.VIEW_ROOT_RES = Res.AvatarShopScene

local PlayerAnimations = {"mapidle","mapwalk","style1","mapmove","angry","celebrate","confusion","happy","seriously"}

function ClassRef:init()
    self._ui.bg:setContentSize(display.size)
    display.setCascadeOpacityEnabled(self._ui.Panel, true)

    self._ui.Button_close:addClickEventListener(function()
            self:closeView()
        end)

    self._showHeadBtn = self._ui["Panel/Panel_tick/selected_btn"]
    display.uiAddClick(self._ui.Panel_tick, function()
        local isBright = self._showHeadBtn:isBright()
        self._showHeadBtn:setBright(not isBright)
        local fashionIDs = UD:getFashionIDs(true, not isBright)
        self._baseInfo.fashionIDs = fashionIDs
        self:_refreshPlayer()
    end)

    local costIcon = self._ui["Panel/btn_buy/icon"]
    local iconPath = GD:getResIcon(Enums.lootType.roseGold)
    costIcon:loadTexture(iconPath)

    self._coinRender = ResRender.create(self._ui.Panel_num)
    self._coinRender:setBtnVisible(false)
    self._coinRender:isNeedSetIcon(true)
    self._coinRender:setData({type = Enums.TipsType.daibi, id = 110, num = 0})

    self._costNumText = self._ui["Panel/btn_buy/num"]
    self._buyBtn = self._ui["Panel/btn_buy/Button"]
    self._buyBtn:addClickEventListener(handler(self, self._onClickBuy))

    local btns = {
        self._ui["Panel/selected_btn_2"],
        self._ui["Panel/selected_btn_3"],
        self._ui["Panel/selected_btn_4"],
        self._ui["Panel/selected_btn_1"],
    }
    local isFirst = true
    local function onTabsBtn(index, btn)
        -- 第一次调用忽略掉
        if not isFirst then
            self._curIdx = index
            self:_openShopPanel()
        else
            isFirst = false
        end
    end
    self._tabsBtn = TabsBtn.new(btns, onTabsBtn)
    self._tabsBtn:initSelectStatus()

    --hero touch check
    local touchLayer = display.newLayer()
    touchLayer:setContentSize(display.width,display.height)
    touchLayer:setTouchEnabled(true)
    self:addChild(touchLayer)
    local touchListener = cc.EventListenerTouchOneByOne:create()
    touchListener:registerScriptHandler(function(touch, event)
        local locationX,locationY = touch:getLocation2()
        local playArmature = self._ui.player:getChildByTag(0)
        if playArmature and playArmature:containWorldPoint(locationX,locationY) then
            self:_playNextAnimation()
        end
        return false
    end,cc.Handler.EVENT_TOUCH_BEGAN)
    self:getEventDispatcher():addEventListenerWithSceneGraphPriority(touchListener, touchLayer)
end

function ClassRef:_getMaskLayer()
    if not self._maskLayer then
        local layer = ccui.Layout:create()
        layer:setContentSize(cc.size(display.width, display.height))
        layer:setBackGroundColor(display.COLOR_BLACK)
        layer:setBackGroundColorType(1)
        layer:setTouchEnabled(false)
        layer:setLocalZOrder(999)
        layer:hide()

        self._maskLayer = layer
        self:addChild(layer)
    end
    return self._maskLayer
end

function ClassRef:openAction()
    local maskLayer = self:_getMaskLayer()
    maskLayer:show()
    maskLayer:stopAllActions()
    maskLayer:runAction(cca.fadeOut(0.6))
end

function ClassRef:closeAction(cb)
    local maskLayer = self:_getMaskLayer()
    maskLayer:show()
    maskLayer:stopAllActions()

    local act = cca.seq({cca.fadeIn(0.6), cca.cb(function()
            executeFunc(cb)
        end)})
    maskLayer:runAction(act)
end

function ClassRef:reOpen()
    self:_refreshCost()
end

function ClassRef:refreshRedPoint()
    local baseInfo = self._baseInfo
    local shopInfo = self._shopInfos[baseInfo.gender]

    local isFaceNew = shopInfo:isFaceNew()
    local isHairNew = shopInfo:isHairNew()
    local isHairColorNew = shopInfo:isHairColorNew(baseInfo.hairID)
    self._tabsBtn:getBtn(1):getChildByName("dot"):setVisible(isFaceNew)
    self._tabsBtn:getBtn(2):getChildByName("dot"):setVisible(isHairNew)
    self._tabsBtn:getBtn(3):getChildByName("dot"):setVisible(isHairColorNew)
end

function ClassRef:buyAvatarSuccess()
    local baseInfo = self._baseInfo
    local shopInfo = self._shopInfos[baseInfo.gender]
    local hairColorID = shopInfo:getHairColorID(baseInfo.hairID, baseInfo.hairColorID)
    self._initIds = {baseInfo.faceID, baseInfo.hairID, hairColorID, baseInfo.gender}
    self._isActives = {1,1,1,1}
    self._costNums = {0,0,0,0}
    self:_refreshCost()
end

-- shopInfos = AvatarShopInfo
-- baseInfo = UserBaseInfo
function ClassRef:refresh(shopInfos, baseInfo)
    self._shopInfos = shopInfos
    self._baseInfo = baseInfo

    local shopInfo = shopInfos[baseInfo.gender]
    local hairColorID = shopInfo:getHairColorID(baseInfo.hairID, baseInfo.hairColorID)
    self._initIds = {baseInfo.faceID, baseInfo.hairID, hairColorID, baseInfo.gender}
    self._isActives = {1,1,1,1}
    self._costNums = {0,0,0,0}
    self:_refreshCost()

    self:_refreshPlayer()
end

-- 刷新shopPanel
function ClassRef:refreshShopPanel()
    if self._curIdx then
        self:_openShopPanel()
    end
end

function ClassRef:_onClickBuy()
    local costTotalNum = table.sum(self._costNums)
    local isAllActive = table.sum(self._isActives) == 4
    if costTotalNum > self._haveNum then
        display.pushToast(L("barber_shoptips5"))
    elseif costTotalNum == 0 then
        local tipStr = isAllActive and L("barber_shoptips6") or L("barber_shoptips7")
        display.pushToast(tipStr)
    else
        local baseInfo = self._baseInfo
        local shopInfo = self._shopInfos[baseInfo.gender]
        if not isAllActive then
            local dlg = display.newConfirmDialog(L("barber_shoptips8"),
                    function() -- 确定
                        -- 性别都是解锁的，这里可以不需要考虑性别了
                        for i,v in ipairs(self._isActives) do
                            if v == 0 then
                                local initId = self._initIds[i]
                                if i == 1 then
                                    self:_changeAvatar(shopInfo:getFaceItemByID(initId))
                                elseif i == 2 then
                                    self:_changeAvatar(shopInfo:getHairItemByID(initId))
                                elseif i == 3 then
                                    self:_changeAvatar(shopInfo:getHairColorItemByID(baseInfo.hairID, initId))
                                end
                            end
                        end
                        self:_refreshPlayer()
                        self:_refreshCost()
                    end)
            UIHandler:addPopupUi(dlg, "AvatarShopDlg")
        else
            local hairColorID = shopInfo:getHairColorID(baseInfo.hairID, baseInfo.hairColorID)
            local params = {
                faceID = baseInfo.faceID,
                hairID = baseInfo.hairID,
                hairColorID = hairColorID,
                gender = baseInfo.gender
            }
            self:_playChangeEffect(params)
        end
    end
end

function ClassRef:_playChangeEffect(params)
    local changeArmature = self._changeArmature
    if not changeArmature then
        changeArmature = Armature.create({
            path = Res.Effect_Ride.dir,
            armatureName = Res.Effect_Ride.name,
        })
        changeArmature:setScale(1.5)
        changeArmature:setPosition(self._ui.player:getPosition())
        self._root:addChild(changeArmature)
        self._changeArmature = changeArmature
    end

    executeFunc(self._onOperate, "im_visible", false)
    self._buyBtn:setTouchEnabled(false)
    local outAct = cca.seq({cca.fadeOut(0.2), cca.delay(0.5), cca.fadeIn(0.2), cca.cb(function()
            self._buyBtn:setTouchEnabled(true)
            executeFunc(self._onOperate, "im_visible", true)
        end)})
    self._ui.Panel:runAction(outAct)

    changeArmature:setVisible(true)
    local ani = {
        name = Res.Effect_Ride.action,
        playTimes = 1,
        completeCallback = function(sender)
            executeFunc(self._onOperate, "buy_avatar", params)

            self:_playChangeSucessEffect()
        end
    }
    changeArmature:playAni(ani)
end

function ClassRef:_playChangeSucessEffect()
    local tipNode = self._tipNode
    if not tipNode then
        tipNode = cc.CSLoader:createNode(Res.DesktopCountDownScene, true)
        display.setCascadeOpacityEnabled(tipNode, true)
        self._tipNode = tipNode
        self:addChild(tipNode, 10)
        tipNode:setContentSize(display.size)
        ccui.Helper:doLayout(tipNode)
        tipNode:findChild("Panel/Text_1"):setString(L("barber_shoptips11"))
    end

    local timeline = tipNode:getTimeline()
    timeline:gotoFrameAndPlay(0, false)
end

function ClassRef:_refreshCost()
    self._coinRender:refreshNum()

    local costTotalNum = table.sum(self._costNums)
    local haveNum = UD:getDaibiValue(Enums.lootType.roseGold)
    self._haveNum = haveNum

    self._costNumText:setString(string.format(L("barber_shoptips10"), costTotalNum))
    local textColor = haveNum >= costTotalNum and display.COLOR_WHITE or display.COLOR_RED_NOTICE
    self._costNumText:setTextColor(textColor)
end

function ClassRef:_refreshPlayer()
    if not self._baseInfo then return end
    local hero = self._ui.player:getChildByTag(0)
    if hero and self._curIdx and self._curIdx == 1 then
        -- 换脸
        AvatarFactory.changeFace(hero, self._baseInfo)
    else
        self._ui.player:removeAllChildren()

        local hero = AvatarFactory.createHero(self._baseInfo)
        self._ui.player:addChild(hero)
        hero:setTag(0)
        self._playIndex = nil
        self:_playNextAnimation()
    end
end

function ClassRef:_playNextAnimation()
    local hero = self._ui.player:getChildByTag(0)
    if hero then
        local animations = PlayerAnimations
        if not self._playIndex or self._playIndex >= #animations then
            self._playIndex = 0
        end
        self._playIndex = self._playIndex + 1
        hero:playAni({name=animations[self._playIndex],next="mapidle"})
    end
end

function ClassRef:_shopPanelOperate(op, data)
    if op == "item_select" then
        self:_changeAvatar(data)
        self:_refreshPlayer()
        self:_refreshCost()
    elseif op == "get_resource" then
        executeFunc(self._onOperate, "get_resource", data:getResource())
    end
end

-- item = AvatarShopItem
function ClassRef:_changeAvatar(item)
    local baseInfo = self._baseInfo
    local shopInfo = self._shopInfos[baseInfo.gender]

    local id = item:getId()
    local shopType = item:getShopType()
    local costNum = 0
    if id ~= self._initIds[shopType] and item:isActive() then
        costNum = item:getCostNum()
    end
    self._costNums[shopType] = costNum
    self._isActives[shopType] = item:isActive() and 1 or 0

    if shopType == 1 then
        baseInfo.faceID = id
    elseif shopType == 2 then
        baseInfo.hairID = id
    elseif shopType == 3 then
        baseInfo.hairColorID = shopInfo:getHairColorIndex(baseInfo.hairID, id)
    elseif shopType == 4 then
        baseInfo.gender = id

        -- 切换性别，其他的都强制选择第一项
        local initIds = self._initIds
        shopInfo = self._shopInfos[baseInfo.gender]
        self:_changeAvatar(shopInfo:getFaceItemByID(initIds[1]))
        local hairItem = shopInfo:getHairItemByID(initIds[2])
        self:_changeAvatar(hairItem)
        self:_changeAvatar(shopInfo:getHairColorItemByID(hairItem:getId(), initIds[3]))
    end
end

function ClassRef:_openShopPanel()
    -- 点击过后移除红点
    self._tabsBtn:getBtn(self._curIdx):getChildByName("dot"):setVisible(false)

    local shopPanel = self._shopPanel
    if not shopPanel then
        shopPanel = AvatarShopPanel.create()
        local btn = self._tabsBtn:getBtn(1)
        local width, height = btn:getContentSize2()
        shopPanel:setPositionX(btn:getPositionX() - width / 2 - 10)
        shopPanel:onOperate(handler(self, self._shopPanelOperate))
        self._ui.Panel:addChild(shopPanel)
        self._shopPanel = shopPanel

        display.nodeRemoveForNotHit(shopPanel, function()
            shopPanel:setVisible(false)
            self._tabsBtn:initSelectStatus()
            self._curIdx = nil
        end)
    end

    local baseInfo = self._baseInfo
    local shopInfo = self._shopInfos[baseInfo.gender]
    local items, curId
    if self._curIdx == 1 then
        items = shopInfo:getFaceItems()
        curId = baseInfo.faceID
    elseif self._curIdx == 2 then
        items = shopInfo:getHairItems()
        curId = baseInfo.hairID
    elseif self._curIdx == 3 then
        local hairItem = shopInfo:getHairItemById(baseInfo.hairID)
        items = hairItem:getHairColorItems()
        curId = hairItem:getHairColorID(baseInfo.hairColorID)
    elseif self._curIdx == 4 then
        items = shopInfo:getGenderItems()
        curId = baseInfo.gender
    end
    shopPanel:refreshContent(items, self._initIds[self._curIdx], curId)
    shopPanel:setName(AVATAR_SHOP_NAMES[self._curIdx])

    local btn = self._tabsBtn:getBtn(self._curIdx)
    shopPanel:refreshPosY(btn:getPositionY())
    shopPanel:setVisible(true)
end

return ClassRef
